package collector

import (
	"fmt"
	"http_monitor/models"
	"http_monitor/rule"
	"http_monitor/utils"
	"strconv"
	"sync"
	"time"
)

func GetRequestTime() (chan map[string]interface{}, error) {
	var wg sync.WaitGroup
	fmt.Println(time.Now())

	result, err := models.GetApis()
	if err != nil {
		return nil, err
	}
	c := make(chan map[string]interface{}, len(result))
	for _, v := range result {
		wg.Add(1)

		go func(v models.Apis) {
			result := make(map[string]interface{})
			defer wg.Done()
			nanosecond := time.Now().Nanosecond()
			body, doTime, code, _ := utils.HttpRequest(v.Url+"?t="+strconv.Itoa(nanosecond), v.Timeout, v.Method, "")
			factory := rule.Factory{Rule: v.VerifyRule}
			rule := factory.GetRule()
			result["requestTime"] = doTime
			source := ""
			if v.VerifyType == "body" {
				source = body

			} else if v.VerifyType == "code" {
				source = strconv.Itoa(code)
			}
			if !rule.Verify(source, v.VerifyValue) {
				result["requestTime"] = -5000
			}
			result["models"] = v

			if v.VerifyRule == "code" {

			}

			c <- result

		}(v)

	}
	wg.Wait()
	return c, nil
}
